package com.crack.nga2.activity;

import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.support.annotation.NonNull;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.view.menu.MenuPopupHelper;
import android.support.v7.widget.ListPopupWindow;
import android.support.v7.widget.PopupMenu;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.crack.nga2.R;
import com.crack.nga2.activity.userCenter.PostStep1Activity;
import com.crack.nga2.custom.HeadLayoutImpl;
import com.crack.nga2.custom.ILoadingLayout;
import com.crack.nga2.entity.Floor;
import com.crack.nga2.entity.Theme;
import com.crack.nga2.entity.User;
import com.crack.nga2.entity.data.FloorData;
import com.crack.nga2.fragment.FloorFragment;
import com.crack.nga2.span.EmotionGetterImpl;
import com.crack.nga2.span.PidClickImpl;
import com.crack.nga2.span.SpanHelper;
import com.crack.nga2.span.UidClickImpl;
import com.crack.nga2.span.UrlClickImp;
import com.crack.nga2.utils.GlobalConst;
import com.crack.nga2.utils.HttpParams;
import com.crack.nga2.volley.CollectRequest;
import com.crack.nga2.volley.ReadThemeRequest;
import com.tencent.mm.sdk.modelmsg.SendMessageToWX;
import com.tencent.mm.sdk.modelmsg.WXMediaMessage;
import com.tencent.mm.sdk.modelmsg.WXWebpageObject;
import com.tencent.tauth.IUiListener;
import com.tencent.tauth.UiError;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 阅读主题
 * 呈现主题帖具体内容
 */
public class FloorActivity extends BaseActivity implements ViewPager.OnPageChangeListener, PopupMenu.OnMenuItemClickListener {
    private ViewPager viewPager;
    private TextView pageInfo;
    private Theme theme;
    private int fid;
    private String forum_name;
    private int tid;
    private int page_index;
    private int page_size;
    private FloorPageAdapter adapter;
    private List<FloorFragment> fragments = new ArrayList<>();
    //标记是否第一次获取数据
    private boolean flag;
    private ILoadingLayout header;
    //弹出窗口
    private PopupWindow popupWindow;
    private boolean windowIsOpen;
    //弹出式菜单
    private PopupMenu popupMenu;
    private MenuPopupHelper helper;

    private SpanHelper spanHelper = new SpanHelper();

    private RequestQueue mQueue;

    private Map<Integer, User> userMap = new HashMap<>();
    private List<Floor> floorList = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        tid = getIntent().getIntExtra("theme", -1);
        if (tid == -1) {
            Toast.makeText(this, "贴子不存在", Toast.LENGTH_SHORT).show();
            finish();
            return;
        }
        mQueue = NgaApplication.getQueue();
        initSpanHelper();
        adapter = new FloorPageAdapter(getSupportFragmentManager());
        setContentView(R.layout.activity_floor);

        initViews();
        View view = findViewById(R.id.refresh_header);
        header = new HeadLayoutImpl(this, view);
        header.startRefresh();
        getData(1);
    }

    /**
     * 是否切换主题
     */
    private boolean isSetTheme = false;

    private void initViews() {
        viewPager = (ViewPager) findViewById(R.id.viewPager);
        if (isSetTheme) {
            adapter.notifyDataSetChanged();
        } else {
            viewPager.setAdapter(adapter);
        }
        if (page_index != 0) {
            viewPager.setCurrentItem(page_index - 1);
        }
        pageInfo = $(R.id.tv_page_info);
        pageInfo.setText(page_index + "/" + page_size);
        viewPager.addOnPageChangeListener(this);
        View view = $(R.id.action_setting);
        initPopupMenu(view);
    }

    /**
     * 初始化url点击事件、pid图片点击事件、uid图片点击事件、表情载入
     */
    private void initSpanHelper() {
        spanHelper.urlClick = new UrlClickImp() {
            @Override
            public void doClick(String url) {
                if (url == null) {
                    return;
                }
                if (url.matches("http://bbs.ngacn.cc/read.php\\?tid=\\d+") || url.matches("read.php\\?tid=\\d+")) {
                    int index = url.indexOf("tid=");
                    if (index != -1) {
                        String tidStr = url.substring(index + "tid=".length());
                        if (tidStr.matches("\\d+")) {
                            int tid = Integer.parseInt(tidStr);
                            Intent intent = new Intent(FloorActivity.this, FloorActivity.class);
                            intent.putExtra("theme", tid);
                            startActivity(intent);
                            return;
                        }
                    }
                } else {
                    Intent intent = new Intent(Intent.ACTION_VIEW);
                    intent.setData(Uri.parse(url));
                    startActivity(intent);
                }
            }
        };
        spanHelper.emotionGetter = new EmotionGetterImpl(this);
        spanHelper.pidClick = new PidClickImpl() {
            @Override
            public void doClick(View widget, int pid, int tid, int lou) {
                Floor clickFloor = null;
                for (Floor floor : floorList) {
                    if (floor.getPid() == pid) {
                        clickFloor = floor;
                        break;
                    }
                }
                if (clickFloor != null) {
                    View view = View.inflate(FloorActivity.this, R.layout.floor_popup_window, null);
                    TextView tvQuote = (TextView) view.findViewById(R.id.tv_quote);
                    TextView tvReply = (TextView) view.findViewById(R.id.tv_content);
                    if (TextUtils.isEmpty(clickFloor.getQuote())) {
                        tvQuote.setVisibility(View.GONE);
                    } else {
                        tvQuote.setText(clickFloor.getQuote());
                    }
                    tvReply.setText(clickFloor.getSp());
                    PopupWindow popupWindow = new PopupWindow(view, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
                    popupWindow.setTouchable(true);
                    popupWindow.setTouchInterceptor(new View.OnTouchListener() {
                        @Override
                        public boolean onTouch(View v, MotionEvent event) {
                            return false;
                        }
                    });
                    popupWindow.setFocusable(true);
                    popupWindow.setBackgroundDrawable(getResources().getDrawable(R.drawable.bg_board));
                    popupWindow.showAsDropDown(widget, 0, -150);
                }
            }
        };
        spanHelper.uidClick = new UidClickImpl() {
            @Override
            public void doClick(View widget, int uid) {
                User user = userMap.get(uid);
                if (user != null) {
                    Intent intent = new Intent(FloorActivity.this, OtherUserActivity.class);
                    intent.putExtra("user", user);
                    startActivity(intent);
                }
            }
        };
    }

    public void getData(final int page) {
        String url = GlobalConst.BASE_URL + "read.php?" + getHttpParams(page).toString() + "&v2";
        mQueue.add(new ReadThemeRequest(Request.Method.GET, url,
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        header.stopRefresh();
                        header.getView().setVisibility(View.GONE);
                    }
                },
                new Response.Listener<FloorData>() {
                    @Override
                    public void onResponse(FloorData response) {
                        if (!flag) {
                            flag = true;
                            theme = response.theme;
                            page_size = response.theme.getReplies() / 20 + 1;
                            for (int i = 0; i < page_size; i++) {
                                FloorFragment fragment = new FloorFragment();
                                fragment.setPage(i + 1);
                                fragments.add(fragment);
                            }
                            page_index = 1;
                            pageInfo.setText(page_index + "/" + page_size);
                            adapter.notifyDataSetChanged();
                            header.stopPull();
                            header.stopRefresh();
                            header.getView().setVisibility(View.GONE);
                        }
                        userMap.putAll(response.getUsers());
                        floorList.addAll(response.getFloors());
                        fragments.get(page - 1).setData(response);
                    }
                }, spanHelper));
    }

    /**
     * 下一页
     */
    public void nextPage() {
        page_index++;
        viewPager.setCurrentItem(page_index - 1);
    }


    @NonNull
    private HttpParams getHttpParams(int page) {
        HttpParams params = new HttpParams();
        params.put("tid", tid);
        params.put("page", page);
        params.put("lite", "js");
        return params;
    }


    /**
     * 一般按钮的点击监听
     */
    public void doClick(View view) {
        switch (view.getId()) {
            case R.id.tv_page_info:
                showPopupWindowForPage();
                break;
            case R.id.reply:
                //回复主题
                Intent intent = new Intent(this, PostStep1Activity.class);
                intent.putExtra("action", "reply");
                intent.putExtra("fid", theme.getFid());
                intent.putExtra("tid", theme.getTid());
                startActivity(intent);
                break;
            case R.id.action_return:
                finishForAnimation();
                break;
            case R.id.action_setting:
                popupMenu.show();
                movePopupMenu();
                break;
            case R.id.iv_gift:
                clickPopupPid = (int) view.getTag();
                break;
            case R.id.iv_quote:
                clickPopupPid = (int) view.getTag();
                intent = new Intent(this, PostStep1Activity.class);
                intent.putExtra("action", "quote");
                intent.putExtra("pid", clickPopupPid);
                intent.putExtra("fid", theme.getFid());
                intent.putExtra("tid", theme.getTid());
                startActivity(intent);
                break;
            case R.id.iv_more:
                //点击显示更多按钮 弹出菜单
                ImageView imageView = (ImageView) view;
                //弹出窗口
                if (popupWindow == null) {
                    initPopupWindowForMore();
                }
                int id = (int) view.getTag();
                windowIsOpen = true;
                iv_more = imageView;
                iv_more.setImageResource(R.drawable.cos_ico);
                popupWindow.showAsDropDown(imageView, 0, -220);
                clickPopupPid = id;
                break;
            case R.id.tv_user_name:
                int uid;
                Object object = view.getTag();
                if (object instanceof Integer) {
                    uid = (int) object;
                    User user = userMap.get(uid);
                    if (user != null) {
                        intent = new Intent(this, OtherUserActivity.class);
                        intent.putExtra("user", user);
                        startActivity(intent);
                    }
                }

                break;
        }
    }

    /**
     * 点击page按钮
     */
    private void showPopupWindowForPage() {
        View pagePopupView = View.inflate(this, R.layout.activity_floor_page_popup_winow, null);
        ListView listView = (ListView) pagePopupView.findViewById(R.id.listView);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

            }
        });
        PopupWindow pageWindow = new PopupWindow(pagePopupView, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        pageWindow.setBackgroundDrawable(getResources().getDrawable(R.drawable.main_bg));
        pageWindow.setTouchable(true);
        pageWindow.setFocusable(true);
        pageWindow.showAsDropDown(pagePopupView, 0, 50);
    }

    /**
     * 初始化弹出式菜单
     *
     * @param view 点击的view
     */
    private void initPopupMenu(View view) {
        popupMenu = new PopupMenu(this, view, Gravity.TOP);
        popupMenu.inflate(R.menu.menu_floor_setting);
        try {
            //强制显示图标
            Field field = popupMenu.getClass().getDeclaredField("mPopup");
            field.setAccessible(true);
            helper = (MenuPopupHelper) field.get(popupMenu);
            helper.setForceShowIcon(true);
        } catch (Exception e) {
            e.printStackTrace();
        }
        popupMenu.setOnMenuItemClickListener(this);
    }

    /**
     * 弹出式菜单点击事件监听
     */
    @Override
    public boolean onMenuItemClick(MenuItem item) {
        Intent intent;
        switch (item.getItemId()) {
            case R.id.menu_collect:
                //收藏
                Map<String, String> params = new HashMap<>();
                params.put("__lib", "topic_favor");
                params.put("__act", "topic_favor");
                params.put("action", "add");
                params.put("tid", String.valueOf(theme.getTid()));
                params.put("lite", "js");
                mQueue.add(new CollectRequest(params, new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        Log.i("collect", response);
                        Toast.makeText(FloorActivity.this, "收藏成功", Toast.LENGTH_SHORT).show();
                    }
                }));
                break;
            case R.id.menu_font_size:
                //字号
                initFontSettingLayout();
                fontPopupWindow.showAtLocation((View) $(R.id.rootView), Gravity.BOTTOM, 0, 0);
                break;
            case R.id.menu_mode:
                //夜间模式
                break;
            case R.id.menu_remind:
                //提醒
                intent = new Intent(this, RemindActivity.class);
                startActivity(intent);
                break;
            case R.id.menu_message:
                //消息
                intent = new Intent(this, MessageActivity.class);
                startActivity(intent);
                break;
            case R.id.menu_sina:
                //新浪微博
                break;
            case R.id.menu_weixin_circle:
                //朋友圈
                shareToWX(1);
                break;
            case R.id.menu_weixin_friends:
                //微信好友
                shareToWX(0);
                break;
            case R.id.menu_qq:
                //qq分享
                Bundle bundle = new Bundle();
                bundle.putString("title", theme.getSubject());
                bundle.putString("targetUrl", "http://bbs.ngacn.cc/read.php?tid=" + tid);
                bundle.putString("imageUrl", "http://cdn.formidapps.com/icon/zjDBCqEw-64.cs.jpg");
                bundle.putString("summary", "来自于NGA精英玩家论坛");
                NgaApplication.mTencent.shareToQQ(this, bundle, new IUiListener() {
                    @Override
                    public void onComplete(Object o) {
                        Log.i("qq", o.toString());
                    }

                    @Override
                    public void onError(UiError uiError) {
                        Log.i("qq", uiError.toString());
                    }

                    @Override
                    public void onCancel() {
                        Log.i("qq", "取消");
                    }
                });
                break;
            case R.id.menu_copy_link:
                String url = "http://bbs.nga.cn/read.php?tid=" + tid;
                //复制链接
                ClipboardManager cmb = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
                cmb.setText(url);
                Toast.makeText(FloorActivity.this, "复制链接成功:" + url, Toast.LENGTH_SHORT).show();
                break;
        }
        return false;
    }

    private ImageView[] fontButtons = new ImageView[4];

    private PopupWindow fontPopupWindow;

    private void initFontSettingLayout() {
        if (fontPopupWindow == null) {
            View fontLayout = View.inflate(this, R.layout.popupwindow_font_setting, null);
            fontPopupWindow = new PopupWindow(fontLayout, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
            fontButtons[0] = $(fontLayout, R.id.font_small);
            fontButtons[1] = $(fontLayout, R.id.font_normal);
            fontButtons[2] = $(fontLayout, R.id.font_larget);
            fontButtons[3] = $(fontLayout, R.id.font_more_larget);
            for (int i = 0; i < 4; i++) {
                fontButtons[i].setOnClickListener(new FontClickListener());
            }
        }
        fontPopupWindow.setTouchable(true);
        fontPopupWindow.setTouchInterceptor(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                return false;
            }
        });
        fontPopupWindow.setFocusable(true);
        fontPopupWindow.setBackgroundDrawable(getResources().getDrawable(R.drawable.none));
    }

    private class FontClickListener implements View.OnClickListener {

        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.font_small:
                    CURRENT_THEME = THEME_SMALL_FONT;//0
                    break;
                case R.id.font_normal:
                    CURRENT_THEME = THEME_NORMAL_FONT;//1
                    break;
                case R.id.font_larget:
                    CURRENT_THEME = THEME_LARGET_FONT;//2
                    break;
                case R.id.font_more_larget:
                    CURRENT_THEME = THEME_MORE_LARGET_FONT;//3
                    break;
            }
            for (int i = 0; i < 4; i++) {
                if (i == CURRENT_THEME) {
                    fontButtons[i].setImageResource(R.drawable.diandian_on);
                } else {
                    fontButtons[i].setImageResource(R.drawable.none);
                }
            }
            setFontSize(CURRENT_THEME);
        }
    }


    private void setFontSize(int themeIndex) {
        setCurrentTheme(themeIndex);
        isSetTheme = true;
        initViews();
    }


    private void shareToWX(final int flag) {
        new Thread() {
            @Override
            public void run() {
                WXWebpageObject object = new WXWebpageObject();
                object.webpageUrl = "http://bbs.ngacn.cc/read.php?tid=" + tid;
                WXMediaMessage mediaMessage = new WXMediaMessage(object);
                mediaMessage.title = theme.getSubject();
                mediaMessage.description = "来自于NGA精英玩家论坛";
//                mediaMessage.setThumbImage(((BitmapDrawable) (getResources().getDrawable(R.drawable.nga_bg))).getBitmap());
                SendMessageToWX.Req req = new SendMessageToWX.Req();
                req.transaction = String.valueOf(System.currentTimeMillis());
                req.message = mediaMessage;
                req.scene = flag == 0 ? SendMessageToWX.Req.WXSceneSession : SendMessageToWX.Req.WXSceneTimeline;
                NgaApplication.mIwxApi.sendReq(req);
            }
        }.start();

    }


    /**
     * 移动弹出式菜单
     */
    private void movePopupMenu() {
        try {
            Field fListPopup = helper.getClass().getDeclaredField("mPopup");
            fListPopup.setAccessible(true);
            ListPopupWindow window = (ListPopupWindow) fListPopup.get(helper);
            window.setVerticalOffset(-70);
            window.setHorizontalOffset(200);
            window.show();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 记录点击时所属回复的pid
     */
    private int clickPopupPid;
    /**
     * 记录点击的view
     */
    private ImageView iv_more;

    private void initPopupWindowForMore() {
        View view = View.inflate(this, R.layout.reply_more_popup_window, null);
        popupWindow = new PopupWindow(view, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        popupWindow.setTouchable(true);
        popupWindow.setTouchInterceptor(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                return false;
            }
        });
        popupWindow.setFocusable(true);
        popupWindow.setBackgroundDrawable(getResources().getDrawable(R.drawable.main_bg));
        popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                if (windowIsOpen) {
                    windowIsOpen = false;
                    iv_more.setImageResource(R.drawable.exp_ico);
                }
            }
        });
    }

    /**
     * 点击弹出窗口按钮
     */
    public void doClickMore(View view) {
        Intent intent;
        switch (view.getId()) {
            case R.id.more_only:
                //只看Ta
                break;
            case R.id.more_sign:
                //签名
                break;
            case R.id.more_reply:
                //回复
                intent = new Intent(this, PostStep1Activity.class);
                intent.putExtra("action", "reply");
                intent.putExtra("pid", clickPopupPid);
                intent.putExtra("fid", theme.getFid());
                intent.putExtra("tid", theme.getTid());
                startActivity(intent);
                break;
            case R.id.more_comment:
                //评论
                intent = new Intent(this, PostStep1Activity.class);
                intent.putExtra("action", "reply");
                intent.putExtra("pid", clickPopupPid);
                intent.putExtra("fid", theme.getFid());
                intent.putExtra("tid", theme.getTid());
                intent.putExtra("commend", 1);
                startActivity(intent);
                break;
            case R.id.more_report:
                //举报
                break;
        }
    }

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    @Override
    public void onPageSelected(int position) {
        page_index = position + 1;
        if (!fragments.get(position).getFlag()) {
            getData(page_index);
        }
        StringBuilder sb = new StringBuilder();
        sb.append(page_index).append("/").append(page_size);
        pageInfo.setText(sb);
    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }


    private class FloorPageAdapter extends FragmentPagerAdapter {

        public FloorPageAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            return fragments.get(position);
        }

        @Override
        public int getCount() {
            return fragments.size();
        }

        @Override
        public int getItemPosition(Object object) {
            return POSITION_NONE;
//            return super.getItemPosition(object);
        }

        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            return super.instantiateItem(container, position);
        }
    }

}
